<?php

namespace app\cps\service;

use app\model\EchoRuleConfig;
use app\model\ResponsibilityPerson;
use app\model\TransferBackRecord;
use app\model\PayRecord;
use app\model\OfficialAccounts;
use think\facade\Db;
use app\model\User;
use app\model\Link;
use app\common\Common;
use app\common\Error;
use app\model\UnpaidUserManualReturn;

// 回传
class EchoService
{
    private $model;
    private $responsibilityPersonModel;
    private $transferBackRecordModel;
    private $payRecordModel;
    private $userModel;
    private $linkModel;
    private $unpaidUserManualReturnModel;
    private $officialAccountsModel;

    public function __construct(EchoRuleConfig $model, ResponsibilityPerson $responsibilityPersonModel, TransferBackRecord $transferBackRecordModel, PayRecord $payRecordModel, User $userModel, Link $linkModel, UnpaidUserManualReturn $unpaidUserManualReturnModel, OfficialAccounts $officialAccountsModel)
    {
        $this->model = $model;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->transferBackRecordModel = $transferBackRecordModel;
        $this->payRecordModel = $payRecordModel;
        $this->userModel = $userModel;
        $this->linkModel = $linkModel;
        $this->unpaidUserManualReturnModel = $unpaidUserManualReturnModel;
        $this->officialAccountsModel = $officialAccountsModel;
    }

    // 获取自定义回传设置列表
    public function getCustomReturnRuleList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
        $appletId = $appletData['applet_id'];

        $cpsUserId = $userInfo['cps_user_id'];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if (!empty($userInfo['is_distributor']) && $userInfo['is_distributor'] == 1) {
            // 分销商
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where = ['applet_id' => $appletId];
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if ($cpsUserId != config('enum.cps_user_id')) {
            $where = ['applet_id' => $appletId];
            $where[] = ['responsibility_person_id', '=', $cpsUserId];
        }

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, responsibility_person_id, name, type, back_rate_type, echo_rate, pass, leak , design_switch, designated_amount_echo, is_open_low_recharge_not_echo, not_echo_recharge_price');

        if (!empty($data['data'])) {
            $responsibilityPersonIds = array_column($data['data'], 'responsibility_person_id');

            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');

            $responsibilityPersonData = array_column($responsibilityPerson, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['responsibility_person_name'] = empty($responsibilityPersonData[$item['responsibility_person_id']]) ? '' : $responsibilityPersonData[$item['responsibility_person_id']];
            }
        }

        return $data;
    }

    // 获取自定义回传设置详情
    public function getCustomReturnRuleDetail(int $id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, responsibility_person_id, name, type, back_rate_type, pass, leak, echo_rate, design_switch, designated_amount_echo, is_open_low_recharge_not_echo, not_echo_recharge_price');
        return $data;
    }

    // 添加/修改自定义回传设置
    public function editCustomReturnRule($params, $userInfo)
    {
        if (!empty($params['echo_rate']) && ($params['echo_rate'] > 100 || $params['echo_rate'] < 0)) {
            return ['message' => Error::ECHO_RATE_INTERVAL_VALUE_ERROR];
        }
        if (empty($params['id'])) {
            $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
            $params['applet_id'] = $appletData['applet_id'];
            $params['created_at'] = time();
            $params['responsibility_person_id'] = $userInfo['cps_user_id'];

            if (!empty($params['designated_amount_echo'])) {
                $designatedAmountEcho = json_decode($params['designated_amount_echo'], true);
            }

            if (!empty($params['design_switch']) && !empty($designatedAmountEcho[0]['price'])) {
                $amountEcho = $price = [];
                $time = time();
                foreach ($designatedAmountEcho as $value) {
                    // 回传金额和回传率需同事存在
                    if (empty($value['price']) || empty($value['rate'])) {
                        return ['code' => Error::FAIL_CODE, 'message' => Error::AMOUNT_OR_RETURN_RATE_CANNOT_BE_EMPTY];
                    }

                    // 判断是否存在填写一样的金额一样的数据
                    if (in_array($value['price'], $price)) {
                        return ['code' => Error::FAIL_CODE, 'message' => Error::THERE_IS_DATA_WITH_THE_SAME_AMOUNT];
                    }
                    $price[] = $value['price'];
                    $amountEcho[] = ['price' => $value['price'], 'rate' => $value['rate'], 'update_time' => $time];
                }
                $params['designated_amount_echo'] = json_encode($amountEcho);
            }
        } else {
            $info = $this->model->getInfoByWhere(['id' => $params['id']], 'echo_rate, pass, leak');
            if ($info['echo_rate'] != $params['echo_rate'] || $info['pass'] != $params['pass'] || $info['leak'] != $params['leak']) {
                $params['edit_echo_time'] = time();
            }
            $params['updated_at'] = time();
        }

        $id = $this->model->edit($params);

        return $id ? true : false;
    }

    // 删除自定义回传设置
    public function deleteCustomReturnRule($id)
    {
        $bool = $this->model->destroy($id);
        return $bool ? true : false;
    }

    // 获取自定义回传设置下拉列表
    public function getCustomBackSetSelectList($userInfo)
    {
        $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
        $appletId = $appletData['applet_id'];
        $where = [];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_id'] == config('enum.cps_user_id')) {
            // $where[] = [];
        } else {
            $where[] = ['applet_id', '=', $appletId];
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
        }

        $data = $this->model->getDataByWhere($where, 'id, name');

        return $data;
    }

    // 修改回传率
    public function editLinkEchoRate($params, $userInfo)
    {
        $linkData = $this->linkModel->getInfoByWhere(['id' => $params['link_id']], 'is_new_back_setting, echo_rate, echo_rule_config_id');
        if ($linkData['is_new_back_setting'] != $params['is_new_back_setting']) {
            return ['message' => Error::OLD_BACK_CANNOT_MODIFY_NEW_BACK];
        }
        if ($linkData['is_new_back_setting'] == 1) {
            if (empty($params['echo_rate'])) {
                return ['message' => Error::ECHO_RATE_NOT_EXIXTS];
            }
        }
        if ($linkData['is_new_back_setting'] == 1) {
            if ($params['echo_rate'] < 0 || $params['echo_rate'] > 100) {
                return ['message' => Error::ECHO_RATE_INTERVAL_VALUE_ERROR];
            }
            $saveData = [
                'id' => $params['link_id'],
                'echo_rate' => $params['echo_rate'],
                'edit_echo_rate_time' => time()
            ];
            $this->linkModel->edit($saveData);
        } else {
            if (!empty($linkData['echo_rule_config_id'])) {
                if (!is_numeric($params['back_rate_type'])) {
                    return ['message' => Error::BACK_RATE_TYPE_NOT_EXIXTS];
                }
                if ($params['back_rate_type'] == 0) {
                    if (empty($params['echo_rate'])) {
                        return ['message' => Error::ECHO_RATE_NOT_EXIXTS];
                    }
                    if ($params['echo_rate'] < 0 || $params['echo_rate'] > 100) {
                        return ['message' => Error::ECHO_RATE_INTERVAL_VALUE_ERROR];
                    }
                    $saveData = [
                        'id' => $linkData['echo_rule_config_id'],
                        'back_rate_type' => 0,
                        'echo_rate' => $params['echo_rate'],
                        'edit_echo_time' => time()
                    ];
                } else {
                    if (empty($params['pass']) || empty($params['leak'])) {
                        return ['message' => Error::PLEASE_WRITE_CYCLE_RATIO];
                    }
                    $saveData = [
                        'id' => $linkData['echo_rule_config_id'],
                        'back_rate_type' => 1,
                        'pass' => $params['pass'],
                        'leak' => $params['leak'],
                        'edit_echo_time' => time()
                    ];
                }
            } else {
                return ['message' => Error::REQUEST_PARAMETER_EXCEPTION];
            }
            $this->model->edit($saveData);
        }

        return [];
    }

    // 修改回传率显示回传数据
    public function showLinkEchoData($params, $userInfo)
    {
        $info = $this->linkModel->getInfoByWhere(['id' => $params['link_id']], 'is_new_back_setting, echo_rate, echo_rule_config_id');
        if ($info['is_new_back_setting'] == 2) {
            $echoRuleConfigData = $this->model->getInfoByWhere(['id' => $info['echo_rule_config_id']], 'back_rate_type, echo_rate, pass, leak');
            $info['echo_rate'] = $echoRuleConfigData['echo_rate'];
            $info['back_rate_type'] = $echoRuleConfigData['back_rate_type'];
            $info['pass'] = $echoRuleConfigData['pass'];
            $info['leak'] = $echoRuleConfigData['leak'];
        }
        return $info;
    }

    // 已回传数据列表
    public function getAlreadyEchoList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $where = [];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $officialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $officialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $officialAccountId];
        }
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }
        // 计划id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 用户id搜索
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        // 投放媒体搜索
        if (!empty($params['media_id'])) {
            $where[] = ['media_id', '=', $params['media_id']];
        }

        // 回传状态搜索
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 回传时间搜索
        if (!empty($params['start_date'])) {
            $startTime = strtotime($params['start_date']);
            $where[] = ['created_at', '>=', $startTime];
        }
        if (!empty($params['end_date'])) {
            $endTime = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['created_at', '<=', $endTime];
        }

        // 是否首单
        if (isset($params['is_first_recharge']) && is_numeric($params['is_first_recharge'])) {
            $where[] = ['is_first_recharge', '=', $params['is_first_recharge']];
        }

        $data = $this->transferBackRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, uid, media_id, pay_id, link_id, is_first_recharge, status, message, echo_rule_config_id, created_at, advertiser_id');

        if ($data['data']) {
            $payIds = array_column($data['data'], 'pay_id');

            $payRecordData = $this->payRecordModel->getInfo(['id' => $payIds], 'id, total_fee, order_no, uid, activation_time');

            $payRecord = array_column($payRecordData, NULL, 'id');

            // $uids = array_column($payRecordData, 'uid');

            // $userInfo = $this->userModel->getBatchDataByWhere(['id' => $uids], 'id, activation_time, created_at');
            // $userData = array_column($userInfo, NULL, 'id');

            $linkIds = array_column($data['data'], 'link_id');
            $linkData = $this->linkModel->getDataByWhere(['id' => $linkIds], 'id, is_new_back_setting, echo_rule_config_id');
            $link = array_column($linkData, NULL, 'id');

            // $echoIds = array_column($linkData, 'echo_rule_config_id');

            // $this->model->getDataByWhere(['id' => ]);

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['pay_price'] = empty($payRecord[$value['pay_id']]) ? 0 : $payRecord[$value['pay_id']]['total_fee'];

                $data['data'][$key]['activation_time'] = empty($payRecord[$value['pay_id']]) ? '' : $payRecord[$value['pay_id']]['activation_time'];
                // $data['data'][$key]['register_time'] = empty($userData[$value['uid']]) ? '' : $userData[$value['uid']]['created_at'];
                $data['data'][$key]['order_no'] = empty($payRecord[$value['pay_id']]) ? '' : $payRecord[$value['pay_id']]['order_no'];

                if (!empty($link[$value['link_id']])) {
                    if ($link[$value['link_id']]['is_new_back_setting'] == 2) {
                        if ($value['echo_rule_config_id'] == -1) {
                            $data['data'][$key]['echo_rule_config_id'] = -1;
                        } else {
                            $echoData = $this->model->getInfoByWhere(['id' => $value['echo_rule_config_id']], 'type');
                            if ($echoData['type'] == 0) {
                                $data['data'][$key]['echo_rule_config_id'] = 0;
                            } else if ($echoData['type'] == 1) {
                                $data['data'][$key]['echo_rule_config_id'] = 1;
                            } else if ($echoData['type'] == 2) {
                                $data['data'][$key]['echo_rule_config_id'] = 2;
                            }
                        }
                    }
                }
            }
        }

        return $data;
    }

    // 未回传数据列表
    public function getNotEchoList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $activationDate = date('Ymd', time() - 7 * 86400);
        $time = strtotime(date('Y-m-d', time() - 180 * 86400));

        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $where = [
            ['is_echo', '=', 0],
            ['status', '=', 1],
            ['link_id', 'EXP', Db::raw('IS NOT NULL')],
            ['advertiser_id', 'EXP', Db::raw('IS NOT NULL')],
            ['activation_date', '>=', $activationDate]
        ];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere([['responsibility_person_id', 'in', $responsibilityPersonIds], ['created_at', '>', $time]], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere([['official_account_id', '=', $officialAccountId], ['responsibility_person_id', 'in', $responsibilityPersonIds], ['created_at', '>', $time]], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere([['official_account_id', '=', $officialAccountId], ['responsibility_person_id', '=', $responsibilityPersonId], ['created_at', '>', $time]], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $officialAccountId];
        }

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }
        // 计划id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 用户id搜索
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        // 是否首单
        if (isset($params['is_first_recharge']) && is_numeric($params['is_first_recharge'])) {
            $where[] = ['is_first_recharge', '=', $params['is_first_recharge']];
        }
        // 用户金额搜索
        if (!empty($params['total_fee'])) {
            $where[] = ['total_fee', '=', $params['total_fee']];
        }
        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, link_id, pay_time, order_no, uid, total_fee, wechat_order_no, advertiser_id, activation_time, is_first_recharge');

        return $data;
    }

    // 手动批量回传
    public function batchEcho($params, $cpsUserInfo)
    {
        $ids = explode(',', $params['id_string']);

        // 获取充值数据
        $payRecord = $this->payRecordModel->getInfo(['id' => $ids], 'id, link_id, total_fee, uid, advertiser_id');

        // 获取用户数据
        $uids = array_column($payRecord, 'uid');
        $userInfo = $this->userModel->getBatchDataByWhere(['id' => $uids], 'id, clickid, open_id , applet_id , back_url');
        $userData = array_column($userInfo, NULL, 'id');

        // 获取链接数据
        $linkIds = array_column($payRecord, 'link_id');
        $link = $this->linkModel->getDataByWhere(['id' => $linkIds], 'id, media_id, is_capitalization, token , video_id');
        $linkData = array_column($link, NULL, 'id');

        $saveData = $paySaveData = [];
        $officialAccountId = $cpsUserInfo['cps_used_official_account_id'];

        foreach ($payRecord as $item) {
            $payRecordData = $this->payRecordModel->getDataByWhere(['uid' => $item['uid'], 'status' => 1, 'link_id' => $item['link_id']], 'id', 'id asc');

            if ($payRecordData['id'] == $item['id']) {
                $isFirstRecharge = 1;
            } else {
                $isFirstRecharge = 0;
            }

            if (!empty($linkData[$item['link_id']]['media_id']) && $linkData[$item['link_id']]['media_id'] == 1 && !empty($userData[$item['uid']]['clickid'])) {
                // 抖音
                if (!empty($linkData[$item['link_id']]['is_capitalization'])) {
                    // 资产化
                    $token = config('tiktok.capitalization.token');
                    $url = config('tiktok.capitalization.url');
                    $timestamp = time();
                    $rand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
                    shuffle($rand);

                    $nonceArray = array_slice($rand, 0, 4);
                    $nonce = implode('', $nonceArray);

                    $collect = [(string)$token, (string)$nonce, (string)$timestamp];
                    usort($collect, 'strcmp');
                    $signature = sha1(implode('', $collect));

                    $body = [
                        'clue_token' => $userData[$item['uid']]['clickid'],
                        'open_id' => $userData[$item['uid']]['open_id'],
                        'event_type' => '2',
                        'props' => [
                            'pay_amount' => intval($item['total_fee'] * 100)
                        ]
                    ];

                    $requestData = json_encode($body);
                    $url = $url . '?timestamp=' . $timestamp . '&nonce=' . $nonce . '&signature=' . $signature;
                    $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                    $data = json_decode($result, true);
                    $status = isset($data['status']) && $data['status'] == 200 ? 1 : 2; // 1成功 2失败
                    $message = !empty($data['message']) ? $data['message'] : '成功'; // 回传巨量的响应提示
                    // 成功回传修改支付数据
                    if (isset($data['status']) && $data['status'] == 200) {
                        $paySaveData[] = [
                            'id' => $item['id'],
                            'is_echo' => 1,
                            'updated_at' => time()
                        ];
                    }
                } else {
                    // 非资产化
                    $url = 'https://analytics.oceanengine.com/api/v2/conversion';

                    $requestData = [
                        'event_type' => 'active_pay',
                        'event_weight' => floatval($item['total_fee']),
                        'context' => [
                            'ad' => [
                                'callback' => $userData[$item['uid']]['clickid']
                            ]
                        ],
                        'properties' => [
                            'pay_amount' => floatval($item['total_fee']),
                            'bill_track_type' => '1'
                        ],
                        'timestamp' => Common::msectime()
                    ];

                    $requestData = json_encode($requestData);
                    $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                    $data = json_decode($result, true);
                    $status = isset($data['code']) && $data['code'] == 0 ? 1 : 2; // 1成功 2失败
                    $message = !empty($data['message']) ? $data['message'] : '成功'; // 回传巨量的响应提示

                    // 成功回传修改支付数据
                    if (isset($data['code']) && $data['code'] == 0) {
                        $paySaveData[] = [
                            'id' => $item['id'],
                            'is_echo' => 1,
                            'updated_at' => time()
                        ];
                    }
                }

                $saveData[] = [
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'media_id' => 1,
                    'link_id' => $item['link_id'],
                    'created_at' => time(),
                    'status' => $status,
                    'message' => $message,
                    'echo_rule_config_id' => -1,
                    'official_account_id' => $officialAccountId,
                    'is_first_recharge' => $isFirstRecharge,
                    'advertiser_id' => $item['advertiser_id']
                ];
            } else if (!empty($linkData[$item['link_id']]['media_id']) && $linkData[$item['link_id']]['media_id'] == 2 && !empty($userData[$item['uid']]['clickid'])) {
                // 快手 https://yiqixie.qingque.cn/d/home/fcACjQFu3lSI1QT7ktc7TCH9e#
                $url = 'http://ad.partner.gifshow.com/track/activate';

                $requestData = [
                    'callback' => $userData[$item['uid']]['clickid'],
                    'event_type' => 3,
                    'event_time' => Common::msectime(),
                    'purchase_amount' => $item['total_fee']
                ];

                $result = Common::_curl($url, $requestData, 'GET', ['json' => 1]);
                $data = json_decode($result, true);

                $status = isset($data['result']) && $data['result'] == 1 ? 1 : 2;
                $message = !empty($data['error_msg']) ? '失败' : '成功';

                $saveData[] = [
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'media_id' => 2,
                    'link_id' => $item['link_id'],
                    'created_at' => time(),
                    'status' => $status,
                    'message' => $message,
                    'echo_rule_config_id' => -1,
                    'official_account_id' => $officialAccountId,
                    'is_first_recharge' => $isFirstRecharge,
                    'advertiser_id' => $item['advertiser_id']
                ];

                // 成功回传修改支付数据
                if (isset($data['result']) && $data['result'] == 1) {
                    $paySaveData[] = [
                        'id' => $item['id'],
                        'is_echo' => 1,
                        'updated_at' => time()
                    ];
                }
            } else if (!empty($linkData[$item['link_id']]['media_id']) && $linkData[$item['link_id']]['media_id'] == 3 && !empty($userData[$item['uid']]['clickid'])) {
                // 百度
                $url = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
                $conversionTypes = [
                    'logidUrl' => 'https://' . config('app.app_host') . '?bd_vid=' . $userData[$item['uid']]['clickid'],
                    'newType' => 118,
                    'convertValue' => intval($item['total_fee'] * 100)
                ];

                $token = $linkData[$item['link_id']]['token'];
                if (empty($token)) {
                    continue;
                }
                $datas = ['token' => $token, 'conversionTypes' => $conversionTypes];
                $requestData = json_encode($datas);
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $data = json_decode($result, true);
                $status = $data['header']['status'] == 0 ? 1 : 2;
                $message = !empty($data['header']['errors']) ? $data['header']['errors']['message'] : '成功';

                $saveData[] = [
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'media_id' => 3,
                    'link_id' => $item['link_id'],
                    'created_at' => time(),
                    'status' => $status,
                    'message' => $message,
                    'echo_rule_config_id' => -1,
                    'official_account_id' => $officialAccountId,
                    'is_first_recharge' => $isFirstRecharge,
                    'advertiser_id' => $item['advertiser_id']
                ];

                // 成功回传修改支付数据
                if (isset($data['header']['status']) && $data['header']['status'] == 0) {
                    $paySaveData[] = [
                        'id' => $item['id'],
                        'is_echo' => 1,
                        'updated_at' => time()
                    ];
                }
            } else if (!empty($linkData[$item['link_id']]['media_id']) && $linkData[$item['link_id']]['media_id'] == 4 && !empty($userData[$item['uid']]['clickid'])) {
                if (empty($userData[$item['uid']]['back_url'])) {
                    return ['message' => Error::RETURN_VALUE_NOT_EXISTS];
                }
                $appletData = Db::name('applet')->where(['id' => $userData[$item['uid']]['applet_id']])->field('app_id')->find();
                $videoData = Db::name('videos')->where(['id' => $linkData[$item['link_id']]['video_id']])->field('name')->find();

                $url = urldecode($userData[$item['uid']]['back_url']);

                $requestData = [
                    'actions' => [[
                        'action_time' => time(),
                        'user_id' => [
                            'wechat_openid' => $userData[$item['uid']]['open_id'],
                            'wechat_app_id' => $appletData['app_id'],
                        ],
                        'trace' => [
                            'click_id' => $userData[$item['uid']]['clickid']
                        ],
                        'action_type' => 'PURCHASE',
                        'action_param' => [
                            'value' => intval($item['total_fee'] * 100),
                            'product_name' => $videoData['name'] . '-比翼鸟'
                        ]
                    ]]
                ];

                if ($isFirstRecharge) {
                    // 首充下单和付费都回传
                    $requestData1 = $requestData;
                    $requestData1['actions'][0]['action_type'] = 'COMPLETE_ORDER';
                    $result1 = Common::curlRequest($url, 'POST', json_encode($requestData1), ['Content-Type: application/json']); // 回传下单
                    $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']); // 回传付费
                } else {
                    // 复充只回传付费
                    $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']); // 回传付费
                }

                $data = json_decode($result, true);

                $status = $data['code'] == 0 ? 1 : 2;
                $message = $data['message'] != 'ok' ? $data['message'] : '成功';

                $saveData[] = [
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'media_id' => 4,
                    'link_id' => $item['link_id'],
                    'created_at' => time(),
                    'status' => $status,
                    'message' => $message,
                    'echo_rule_config_id' => -1,
                    'official_account_id' => $officialAccountId,
                    'is_first_recharge' => $isFirstRecharge,
                    'advertiser_id' => $item['advertiser_id']
                ];

                // 成功回传修改支付数据
                if (isset($data['code']) && $data['code'] == 0) {
                    $paySaveData[] = [
                        'id' => $item['id'],
                        'is_echo' => 1,
                        'updated_at' => time()
                    ];
                }
            }
        }

        // 添加回传记录
        $this->payRecordModel->saveAll($paySaveData);
        // 修改支付数据为已回传
        $this->transferBackRecordModel->saveAll($saveData);

        return [];
    }

    // 未充值用户列表
    public function getNotRechargeUserList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['first_charge_date', '=', null];
        $where[] = ['clickid', 'EXP', Db::raw('IS NOT NULL')];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];

            $backWhere[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];

            $backWhere[] = ['link_id', 'in', $linkIds];
        } else {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId], 'id');
            $linkIds = array_column($linkData, 'id');
            $backWhere[] = ['link_id', 'in', $linkIds];
        }
        // 日期搜索
        if (!empty($params['date'])) {
            $where[] = ['activation_time', '>=', $params['date'] . ' 00:00:00'];
            $where[] = ['activation_time', '<=', $params['date'] . ' 23:59:59'];

            $backWhere[] = ['created_at', '>=', strtotime($params['date'] . ' 00:00:00')];
            $backWhere[] = ['created_at', '<=', strtotime($params['date'] . ' 23:59:59')];
        } else {
            $where[] = ['activation_time', '>', date('Y-m-d') . ' 00:00:00'];

            $backWhere[] = ['created_at', '>', strtotime(date('Y-m-d') . ' 00:00:00')];
        }

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 计划id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        $backWhere[] = ['status', '=', 1];
        $backData = $this->unpaidUserManualReturnModel->getBatchDataByWhere($backWhere, 'uid');
        $uids = array_column($backData, 'uid');
        $where[] = ['id', 'not in', $uids];

        $data = $this->userModel->getPagingDataByWhere($where, $page, $limit, 'id, link_id, activation_time, advertiser_id', 'activation_time desc');
        return $data;
    }

    /**
     * 未支付用户手动回传
     * 
     * @param int uid 用户id
     * @param float return_amount 回传金额
     * @return array
     */
    public function unpaidUserManualReturn($params)
    {
        $uid = $params['uid'];
        $payAmount = $params['return_amount'];

        $transferBackRecord = $this->transferBackRecordModel->getInfoByWhere(['uid' => $uid, 'status' => 1], 'id, created_at');

        if ($transferBackRecord) {
            if (time() - $transferBackRecord['created_at'] < 24 * 3600) {
                return ['message' => Error::THIS_USER_24_HOUR_RETURNED];
            }
        }

        $data = $this->userModel->getInfoById($uid, 'clickid, activation_time, link_id, open_id, advertiser_id');

        if (empty($data['clickid'])) {
            return ['message' => Error::RETURN_VALUE_NOT_EXISTS];
        }

        $activationTime = strtotime($data['activation_time']);
        $d = date('d', $activationTime); // 获取激活时间日期数
        $h = date('H', $activationTime); // 获取激活时间小时数
        if ($h < 23 && date('d') > $d) {
            // 该用户需是今天激活的用户，且激活时间需要在今天晚上23点前
            return ['message' => Error::THIS_USER_ACTIVATION_TIME_NOT_SATISFY_CONDITION];
        }

        $linkData = $this->linkModel->getInfoByWhere(['id' => $data['link_id']], 'media_id, link_switch, token, is_capitalization');

        if ($linkData['link_switch'] == 0) {
            return ['message' => Error::THIS_USER_CORRESPONDING_LINK_CURRENT_DOWN_LAUNCH];
        }

        if ($linkData['media_id'] == 1) {
            // 抖音
            if (!empty($linkData['is_capitalization'])) {
                // 资产化
                $token = config('tiktok.capitalization.token');
                $url = config('tiktok.capitalization.url');
                $timestamp = time();
                $rand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
                shuffle($rand);

                $nonceArray = array_slice($rand, 0, 4);
                $nonce = implode('', $nonceArray);

                $collect = [(string)$token, (string)$nonce, (string)$timestamp];
                usort($collect, 'strcmp');
                $signature = sha1(implode('', $collect));

                $body = [
                    'clue_token' => $data['clickid'],
                    'open_id' => $data['open_id'],
                    'event_type' => '2',
                    'props' => [
                        'pay_amount' => intval($payAmount * 100)
                    ]
                ];

                $requestData = json_encode($body);
                $url = $url . '?timestamp=' . $timestamp . '&nonce=' . $nonce . '&signature=' . $signature;
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $result = json_decode($result, true);
                $status = isset($result['status']) && $result['status'] == 200 ? 1 : 2; // 1成功 2失败
                $message = !empty($result['message']) ? $result['message'] : '成功'; // 回传巨量的响应提示

            } else {
                // 非资产化
                $url = 'https://analytics.oceanengine.com/api/v2/conversion';

                $requestData = [
                    'event_type' => 'active_pay',
                    'event_weight' => floatval($payAmount * 100),
                    'context' => [
                        'ad' => [
                            'callback' => $data['clickid']
                        ]
                    ],
                    'properties' => [
                        'pay_amount' => floatval($payAmount * 100),
                        'bill_track_type' => '1'
                    ],
                    'timestamp' => Common::msectime()
                ];

                $requestData = json_encode($requestData);
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $result = json_decode($result, true);
                $status = isset($result['code']) && $result['code'] == 0 ? 1 : 2;
                $message = !empty($result['message']) ? $result['message'] : '成功';
            }
        } else if ($linkData['media_id'] == 2) {
            // 快手 https://yiqixie.qingque.cn/d/home/fcACjQFu3lSI1QT7ktc7TCH9e#
            $url = 'http://ad.partner.gifshow.com/track/activate';

            $requestData = [
                'callback' => $data['clickid'],
                'event_type' => 3,
                'event_time' => Common::msectime(),
                'purchase_amount' => $payAmount
            ];

            $result = Common::_curl($url, $requestData, 'GET', ['json' => 1]);
            $result = json_decode($result, true);

            $status = isset($result['result']) && $result['result'] == 1 ? 1 : 2;
            $message = !empty($result['error_msg']) ? '失败' : '成功';
        } else if ($linkData['media_id'] == 3) {
            // 百度
            $url = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
            $conversionTypes = [
                'logidUrl' => 'https://' . config('app.app_host') . '?bd_vid=' . $data['clickid'],
                'newType' => 118,
                'convertValue' => intval($payAmount * 100)
            ];

            if (empty($linkData['token'])) {
                return ['message' => Error::BAIDU_LINK_TOKEN_NOT_EXIXTS];
            }
            $datas = ['token' => $linkData['token'], 'conversionTypes' => $conversionTypes];
            $requestData = json_encode($datas);
            $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
            $result = json_decode($result, true);
            $status = $result['header']['status'] == 0 ? 1 : 2;
            $message = !empty($result['header']['errors']) ? $result['header']['errors']['message'] : '成功';
        } else {
            return ['message' => Error::THE_PLATFORM_NOT_OPENED_THIS_FUNCTION];
        }

        $saveData = [
            'uid' => $uid,
            'clickid' => $data['clickid'],
            'media_id' => $linkData['media_id'],
            'link_id' => $data['link_id'],
            'advertiser_id' => $data['advertiser_id'],
            'created_at' => time(),
            'status' => $status,
            'message' => $message,
            'return_amount' => $payAmount
        ];

        $id = Db::name('unpaid_user_manual_return')->insert($saveData);
        return [];
    }

    // 未支付用户手动回传记录列表
    public function unpaidUserManualReturnRecord($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        }

        // 用户id搜索
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 平台搜索
        if (!empty($params['media_id'])) {
            $where[] = ['media_id', '=', $params['media_id']];
        }

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        $data = $this->unpaidUserManualReturnModel->getPagingDataByWhere($where, $page, $limit, 'id, uid, return_amount, media_id, link_id, status, created_at, advertiser_id');

        return $data;
    }

    // 批量修改回传设置
    public function batchUpdateBackSet($params)
    {
        $linkIds = explode(',', $params['link_ids']);

        if (empty($params)) {
            return ['message' => Error::PLEASE_SELECT_UPDATE_BACK_SETTING];
        }

        $data = $this->linkModel->getDataByWhere(['id' => $linkIds], 'id, is_new_back_setting, echo_rule_config_id');

        $saveLinkData = $newSaveBackData = [];
        foreach ($data as $item) {
            $save = $newBackData = [];
            if (isset($params['link_switch']) && is_numeric($params['link_switch'])) {
                $save['link_switch'] = $params['link_switch'];
            }
            if (!empty($params['is_open'])) {
                $save['is_open'] = $params['is_open'];
            }
            if (isset($params['remark'])) {
                $save['remark'] = $params['remark'];
            }
            // if ($item['is_new_back_setting'] == 1) {
            //     // 旧版本
            //     if (isset($params['echo_rule_config_id']) && is_numeric($params['echo_rule_config_id'])) {
            //         $save['echo_rule_config_id'] = $params['echo_rule_config_id'];
            //     }
            //     if (isset($params['echo_rate']) && is_numeric($params['echo_rate'])) {
            //         $save['echo_rate'] = $params['echo_rate'];
            //     }
            //     if (isset($params['is_open_low_recharge_not_echo']) && is_numeric($params['is_open_low_recharge_not_echo'])) {
            //         $save['is_open_low_recharge_not_echo'] = $params['is_open_low_recharge_not_echo'];
            //     }
            //     if (!empty($params['not_echo_recharge_price'])) {
            //         $save['not_echo_recharge_price'] = $params['not_echo_recharge_price'];
            //     }
            // } else {
            //     // 新版本
            //     $newBackData = ['id' => $item['echo_rule_config_id']];
            //     if (isset($params['echo_rule_config_id']) && is_numeric($params['echo_rule_config_id'])) {
            //         $newBackData['type'] = $params['echo_rule_config_id'];
            //     }
            //     // if (!empty($params['back_rate_type'])) {
            //     //     $newBackData['back_rate_type'] = $params['back_rate_type'];
            //     // }
            //     if (isset($params['echo_rate']) && is_numeric($params['echo_rate'])) {
            //         $newBackInfo = $this->model->getInfoByWhere(['id' => $item['echo_rule_config_id']], 'back_rate_type');
            //         if ($newBackInfo['back_rate_type'] == 1) {
            //             $newBackData['back_rate_type'] = 0;
            //         }
            //         $newBackData['echo_rate'] = $params['echo_rate'];
            //     }
            //     if (isset($params['is_open_low_recharge_not_echo']) && is_numeric($params['is_open_low_recharge_not_echo'])) {
            //         $newBackData['is_open_low_recharge_not_echo'] = $params['is_open_low_recharge_not_echo'];
            //     }
            //     if (!empty($params['not_echo_recharge_price'])) {
            //         $newBackData['not_echo_recharge_price'] = $params['not_echo_recharge_price'];
            //     }
            // }
            if ($save) {
                $save['id'] = $item['id'];
                $saveLinkData[] = $save;
            }

            // if ($newBackData) $newSaveBackData[] = $newBackData;
        }

        $num = $this->linkModel->saveAll($saveLinkData);
        // if ($newSaveBackData) $num = $this->model->saveAll($newSaveBackData);
        if (!$num) {
            return ['message' => Error::SETTING_FAIL];
        }

        return [];
    }
}
